from datetime import timedelta
from django.core.paginator import Paginator
from django.http import HttpResponse, HttpResponseRedirect, HttpRequest
from django.shortcuts import render_to_response
from django.utils.translation import ugettext as _
from looptube.utils import fetchYouTubeVideoData, digg_paginator, unescape
from . import commonInit

def init(request):
    # init from commonInit()
    resp = commonInit(request)
    if (HttpResponse == resp.__class__):
        return resp     # commonInit() returned HttpResponse
    contextDict = resp  # commonInit() returned dict
            
    return contextDict

# actions
def similarVideosAction(request):
    #init from init()
    resp = init(request)
    if (HttpResponse == resp.__class__):
        return resp     # init() returned HttpReponse
    contextDict = resp  # init() returned dict

    if (request.GET.__contains__('videoID')):
        similarVideoID = request.GET['videoID']
    else:
        return HttpResponse('')
    similarVideos = fetchYouTubeVideoData(similarVideoID=similarVideoID, onlyLoopable=True)
    contextDict['videoInfos'] = similarVideos
    return render_to_response('relatedvideos.html', contextDict)

def relatedVideosAction(request):
    #init from init()
    resp = init(request)
    if (HttpResponse == resp.__class__):
        return resp     # init() returned HttpReponse
    contextDict = resp  # init() returned dict

    if (request.GET.__contains__('videoID')):
        relatedVideoID = request.GET['videoID']
    else:
        return HttpResponse('')
    relatedVideos = fetchYouTubeVideoData(relatedVideoID=relatedVideoID, onlyLoopable=True)
    contextDict['videoInfos'] = relatedVideos
    return render_to_response('relatedvideos.html', contextDict)

def indexAction(request):
    numPerPage = 25
    
    #init from init()
    resp = init(request)
    if (HttpResponse == resp.__class__):
        return resp     # init() returned HttpReponse
    contextDict = resp  # init() returned dict
    
    queryString = '';
    if (request.GET.__contains__('q')):
        queryString = request.GET['q'].replace(' ', '%20')
        if (request.GET.__contains__('page')):
            try:
                page = int(request.GET['page'])
            except ValueError:
                page = 1
        else:
            page = 1
        start_index = (page-1) * numPerPage + 1
        searchResults = fetchYouTubeVideoData(escapedQueryString=queryString, start_index=start_index, getDetails=True)
        if (None == searchResults):
            searchResults = []
        else:
            for result in searchResults['results']:
                result['duration'] = unicode(timedelta(0, 0, 0, 0, int(result['duration'])))[:-3]
            results = searchResults['results']
            totalResults = searchResults['totalResults']
            startIndex = searchResults['startIndex']
            itemsPerPage = searchResults['itemsPerPage']
            endIndex = startIndex + itemsPerPage - 1
            if (endIndex > totalResults):
                endIndex = totalResults
            maxResults = totalResults
            if (maxResults > 1000):
                maxResults = 1000
            paginator = Paginator(range(0, maxResults), numPerPage)
            contextDict['digg_paginator'] = digg_paginator(paginator, page, numPerPage, '/search?q='+queryString+'&page=')
            contextDict['searchResults'] = results
            contextDict['searchResultsPage'] = paginator.page(page)
            contextDict['totalResults'] = totalResults
            contextDict['startIndex'] = startIndex
            contextDict['endIndex'] = endIndex
    
    contextDict['searchQuery'] = unescape(queryString)
    contextDict['pageTitle'] = _('Search Result for') + ': '+unescape(queryString)
    return render_to_response('search.html', contextDict)
